import socket

def send_request(url, port):
    # 创建TCP socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # 连接服务端
    sock.connect((url, port))
    # 创建请求消息头
    request_url = 'GET / HTTP/1.1\r\nHost: ' + url + '\r\n\r\n'
    # 发送请求
    sock.send(request_url.encode())
    response = b''
    # 接收返回的数据
    rec = sock.recv(4096)
    head, _ = rec.split(b'\r\n\r\n')  
    headers = head.split(b'\r\n')
    for header in headers:
        if header.startswith(b'Content-Length'):
            content_length = int(header.split(b' ')[1])
    sock.close()
    
    headers_str = head.decode()
    status_code =  headers_str.split('HTTP/1.1 ')[1].split(" ")[0]
    return headers_str, status_code

if __name__ == '__main__':
    baidu_url = 'www.baidu.com'
    baidu_port = 80

    headers_str, status_code = send_request(baidu_url, baidu_port)
    print("baidu 状态码:\n", status_code)
    print("baidu headers:\n", headers_str)
